import React, { useEffect } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import useLoadRouter from "./hooks/useLoadRouter";
import { useDispatch, useSelector } from "react-redux";
import { notification } from "antd";

import { SaveUserDetailActions, SaveActiveNamesActions } from "@/store";
import useDebounce from "@/utils/debounce";
export let SocketServer: WebSocket | null = null;
import {

  IDispatch,
  fetchMenuThunk,
  SaveInnerWidthActions,
  fetchDepartmentThunk,
  fetchGetUserListThunk,
  IStore,
} from "@/store";
// import { invoke } from '@tauri-apps/api'
// import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/api/notification';
// let permissionGranted = await isPermissionGranted();
// if (!permissionGranted) {
//   const permission = await requestPermission();
//   permissionGranted = permission === 'granted';
// }
// if (permissionGranted) {
//   // sendNotification('Tauri is awesome!');
//   sendNotification({ title: 'TAURI', body: 'Tauri is awesome!' });
// }
function App() {
  const navigate = useNavigate();
  const dispatch = useDispatch<IDispatch>();
  const userStore = useSelector((state: IStore) => state.user);
  const [api, contextHolder] = notification.useNotification();
  useEffect(() => {
    try {
      // invoke('greet', { name: 'World' }).then((response) => console.log(response))
      const token = localStorage.getItem("token");
      dispatch(SaveInnerWidthActions(window.innerWidth));
      dispatch(fetchDepartmentThunk());
      const user: any = localStorage.getItem("user");
      const d = useDebounce(() => {
        dispatch(SaveInnerWidthActions(window.innerWidth));
      });
      function BackLocation(e: KeyboardEvent) {
        if (e.code == "F12") {
          if (JSON.parse(user)?.id != 1) {
            e.stopPropagation()
            e.preventDefault()
          }
        }
        if (e.code == "Escape") {
          navigate(-1)
        }
      }
      function contextmenu(e) {
        if (JSON.parse(user)?.id != 1) {
          e.stopPropagation()
          e.preventDefault()
        }
      }
      window.addEventListener("resize", d);
      window.addEventListener("keydown", BackLocation)
      // document.addEventListener('contextmenu', contextmenu);
      document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
          // 页面不可见时执行的代码
        } else {
          // 页面可见时执行的代码
          SocketServer && SocketServer.send("fetch order")
          // this.location.reload();
        }
      });
      if (token && user) {
        dispatch(fetchGetUserListThunk());
        const _ = JSON.parse(user);
        if (!_) {
          localStorage.removeItem("token");
          localStorage.removeItem("user");
          navigate("/login");
          return;
        }
        // 检查浏览器是否支持通知
        // if (!("Notification" in window)) {
        //   alert("此浏览器不支持桌面通知");
        // }
        console.log("=> ", _)
        dispatch(SaveUserDetailActions(_));
        dispatch(fetchMenuThunk(_.id));
      } else {
        localStorage.removeItem("token");
      }
      return () => {
        window.removeEventListener("resize", d);
        window.removeEventListener("keydown", BackLocation)
        document.removeEventListener('contextmenu', contextmenu);
      }
    } catch (e) {
      // location.reload();
      console.log("app page error : ", e);

    }
  }, []);
  useEffect(() => {
    if (!SocketServer) {
      console.log("userStore.user", userStore.user)
      if (userStore.user != null) {
        const { user_name } = userStore.user;
        console.log("=> user_name ", user_name)
        SocketServer = new WebSocket(
          "ws://127.0.0.1:12345/ws?token=" + user_name
        );
        SocketServer.onopen = function (e) {
          console.log("socket 链接成功！！！ ");
        };
        SocketServer.onmessage = function (e) {
          const data: any = JSON.parse(e.data);
          console.log("socket message ", data);
          switch (data.type) {
            case "SaveMember":
              dispatch(
                SaveActiveNamesActions(data.data.map((item) => item.ID))
              );
              break;
            case user_name:
              if(data.data){                
                api.info({
                  message: data.msg,
                  description: `还有${data.data}个订单没有查看,打印`,
                  placement: "bottomRight",
                  showProgress: true,
                  // onClose() {
                  //   message.info("前往订单管理，查看抄送订单~");
                  // },
                  onClick() {
                    navigate("/home/order?status=" + "notify");
                  },
                });
              }

              break;
            case "AO":
              console.log("AO res ", data);
              const dataArray: string[] = data.data.map(
                (item) => item.OrderNumber
              );
              dataArray.length &&
                api.info({
                  message: data.msg,
                  description: `您有${dataArray.length
                    }个订单待审核，单号为： ${dataArray.join(" - ")}`,
                  placement: "bottomRight",
                  duration: 10,
                  showProgress: true,
                  onClick() {
                    navigate("/home/audits?timestamp=" + new Date().getTime());
                  },
                  // onClose() {
                  //   message.info("前往审核页面,查看订单!");
                  // },
                });
              break;
          }
        };
        SocketServer.onerror = function (e) {
          console.log("=> 错误， 关闭socket", e);
          SocketServer.close();
          SocketServer = null;
        };
        SocketServer.onclose = function (e) {
          console.log("=> 关闭， 清空socket", e);
          SocketServer = null;
        };
      }
    }
  }, [userStore.user]);
  return (
    <>
      {contextHolder}
      {useLoadRouter()}
      <Outlet />
    </>
  );
}

export default App;
